<template>
  <div class="practice-selection">
    <h2>所有实践活动</h2>
    
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      加载中...
    </div>
    
    <div v-if="error" class="error">
      {{ error }}
    </div>
    
    <el-table v-if="!loading && !error" :data="practices" style="width: 100%">
      <el-table-column prop="praName" label="实践名称" width="180" />
      <el-table-column prop="teacherName" label="指导教师" width="120" />
      <el-table-column prop="courseName" label="关联课程" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button 
            v-if="!row.isJoined"
            type="primary" 
            size="small"
            @click="joinPractice(row.id)"
          >
            加入
          </el-button>
          <el-tag v-else type="success">已加入</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const practices = ref([])
const loading = ref(false)
const error = ref(null)

const getStudentId = async () => {
  const userId = authStore.userId
  if (!userId) {
    error.value = '用户未登录'
    return null
  }

  try {
    loading.value = true
    error.value = null
    
    // 直接调用后端接口获取学生ID
    const response = await fetch(`/api/student/id/by-user/${userId}`)
    if (!response.ok) throw new Error('获取学生ID失败')
    
    const data = await response.json()
    const studentId = data?.data || data?.result || data
    
    if (!studentId) {
      throw new Error('未获取到有效学生ID')
    }
    
    return studentId
  } catch (err) {
    error.value = err.message
    ElMessage.error(error.value)
    return null
  } finally {
    loading.value = false
  }
}

const loadPractices = async () => {
  const studentId = await getStudentId()
  if (!studentId) return

  try {
    loading.value = true
    error.value = null
    
    // 直接调用后端接口获取所有实践
    const response = await fetch(`/api/student/practices?studentId=${studentId}`)
    if (!response.ok) throw new Error('加载实践活动失败')
    
    practices.value = await response.json()
  } catch (err) {
    error.value = err.message
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

const joinPractice = async (practiceId) => {
  const studentId = await getStudentId()
  if (!studentId) return

  try {
    loading.value = true
    
    // 直接调用后端加入实践接口
    const response = await fetch(`/api/student/practices/${practiceId}/join?studentId=${studentId}`, {
      method: 'POST'
    })
    
    if (!response.ok) throw new Error('加入实践失败')
    
    ElMessage.success('加入实践成功')
    await loadPractices() // 刷新列表
  } catch (err) {
    error.value = err.message
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

onMounted(() => {
  loadPractices()
})
</script>

<style scoped>
.practice-selection {
  padding: 20px;
}
.loading, .error {
  margin: 20px 0;
  text-align: center;
}
.error {
  color: red;
}
</style>